Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

230
Visualizações
Why is the "this" keyword in this function not giving an error in JavaScript for duplication?

function makeUser() {
  return {
    name: "John",
    ref() {
      return this;
    }
  };
}

let user = makeUser();

alert(user.ref().name);

From what I've learned from thistutorial, they define as the object before dot and since this is the return value of the function, I thought it would be user.

And this tutorial is defining it as the object that is executing the current function.

I think the object that is executing the current function is user. When you replace this by its value it becomes alert(user.user.name);.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The value of "this" doesn't refer to the name of an object, it refers to the object itself. So there is no "duplication" here, you're just returning an object, which happens to be the same object you started with.

This is perhaps clearer if you separate things out:

function makeUser() {
  // Create an object
  let myObject = {
    name: "John"
  };
  // Create a function which returns that object
  let myFunction = function(){ return myObject; };
  // Store the function on the object
  myObject.ref = myFunction;
  // Return the new object
  return myObject;
}

// Create an object
let user = makeUser();

// Get the name from the object
alert(user.name);

// Call the ref() function, which happens to return the same object
let otherUser = user.ref();
// Get the name again
alert(otherUser.name);

// No matter how many times you call .ref() it will return the same object
alert(user.ref().ref().ref().ref().name);

about 4 years ago · Juan Pablo Isaza Relatório

0

this refers to a object the function function belongs to or window object if it belongs to no objects. in this case ref() function is returning the owner object for e.g.,

when you call ref() it will return like this

{ name: 'John', ref: [Function: ref] }
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda